import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/store'
import { getToken } from '@/utils'
import { login } from '@/api'
import InitPage from '@/pages/init.vue'

const Layout = () => import('@/components/menu/layouts.vue')

const DashboardPage = () => import('@/pages/Dashboard.vue')

const ResourceCategoryPage = () => import('@/pages/resource/resource-category/index.vue')
const ResourceVideosPage = () => import('@/pages/resource/videos/index.vue')
const ResourceImagesPage = () => import('@/pages/resource/images/index.vue')
const ResourceCoursewarePage = () => import('@/pages/resource/courseware/index.vue')

const TestPage = () => import('@/pages/test.vue')
const ErrorPage = () => import('@/pages/error.vue')
const LoginPage = () => import('@/pages/Login.vue')
const ChangePasswordPage = () => import('@/pages/change-password.vue')

const DepartmentPage = () => import('@/pages/department/index.vue')

const MemberPage = () => import('@/pages/member/index.vue')

const SystemConfigPage = () => import('@/pages/system/config.vue')
const SystemAdministratorPage = () => import('@/pages/system/administrator/index.vue')
const SystemAdminrolesPage = () => import('@/pages/system/adminroles/index.vue')
const SystemLogPage = () => import('@/pages/system/adminlog/index.vue')

const CoursePage = () => import('@/pages/course/index.vue')
const CourseUserPage = () => import('@/pages/course/user.vue')

const LicensingPage = () => import('@/pages/licensing.vue')
const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: LoginPage,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: InitPage,  // 使用 InitPage 作为根组件
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        component: Layout,  // Layout 作为 InitPage 的子组件
        children: [
          {
            path: '',
            redirect: '/dashboard'
          },
          {
            path: 'dashboard',
            name: 'Dashboard',
            component: DashboardPage,
            meta: { title: '仪表板' }
          },
          {
            path: 'resource-category',
            name: 'ResourceCategory',
            component: ResourceCategoryPage,
            meta: { title: '分类管理' }
          },
          {
            path: 'videos',
            name: 'ResourceVideos',
            component: ResourceVideosPage,
            meta: { title: '视频' }
          },
          {
            path: 'images',
            name: 'ResourceImages',
            component: ResourceImagesPage,
            meta: { title: '图片' }
          },
          {
            path: 'courseware',
            name: 'ResourceCourseware',
            component: ResourceCoursewarePage,
            meta: { title: '课件' }
          },
          {
            path: 'change-password',
            name: 'ChangePassword',
            component: ChangePasswordPage,
            meta: { title: '修改密码' }
          },
          {
            path: 'member/index',
            name: 'Member',
            component: MemberPage,
            meta: { title: '学员' }
          },
          {
            path: 'department',
            name: 'Department',
            component: DepartmentPage,
            meta: { title: '部门管理' }
          },
          {
            path: 'system/config/index',
            name: 'SystemConfig',
            component: SystemConfigPage,
            meta: { title: '系统配置' }
          },
          {
            path: 'system/administrator',
            name: 'SystemAdministrator',
            component: SystemAdministratorPage,
            meta: { title: '管理人员' }
          },
          {
            path: 'system/adminroles',
            name: 'SystemAdminroles',
            component: SystemAdminrolesPage,
            meta: { title: '管理角色' }
          },
          {
            path: 'system/adminlog',
            name: 'SystemLog',
            component: SystemLogPage,
            meta: { title: '管理日志' }
          },
          {
            path: 'course',
            name: 'Course',
            component: CoursePage,
            meta: { title: '课程' }
          },
          {
            path: 'course/user/:courseId',
            name: 'CourseUser',
            component: CourseUserPage,
            meta: { title: '人员课程' }
          },
          {
            path: 'licensing',
            name: 'Licensing',
            component: LicensingPage,
            meta: { title: '使用许可' }
          },
          {
            path: 'test',
            name: 'Test',
            component: TestPage,
            meta: { requiresAuth: false }
          }
        ]
      },
      {
        path: 'error',
        name: 'Error',
        component: ErrorPage,
        meta: { requiresAuth: false }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    redirect: '/error'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  const token = getToken()

  // console.log('路由导航:', to.path, '认证要求:', to.meta.requiresAuth, '登录状态:', userStore.isLogin)

  // 如果需要认证但未登录
  if (to.meta.requiresAuth && !userStore.isLogin) {
    if (token) {
      // 有token但store中未登录，尝试自动登录
      try {
        const userRes = await login.getUser()
        userStore.loginAction({
          user: userRes.data,
          permissions: userRes.data.permissions || []
        })

        next()
      } catch (error) {
        console.error('自动登录失败', error)
        next('/login')
      }
    } else {
      next('/login')
    }
  } 
  // 如果已登录但访问登录页，重定向到首页
  else if (to.path === '/login' && userStore.isLogin) {
    next('/dashboard')
  } 
  // 其他情况正常放行
  else {
    next()
  }
})

export default router